<?php

namespace app\common\model;

use think\Model;
use think\Db;

class Strategy extends Model
{

    

    

    // 表名
    protected $name = 'strategy';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'is_auto_text',
        'pay_type_text',
        'buy_time_text',
        'pay_time_text'
    ];
    

    
    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2'),'3'=>'亏损预警'];
    }

    public function getIsAutoList()
    {
        return ['1' => __('Is_auto 1'), '2' => __('Is_auto 2')];
    }

    public function getPayTypeList()
    {
        return ['1' => __('Pay_type 1'), '2' => __('Pay_type 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsAutoTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_auto']) ? $data['is_auto'] : '');
        $list = $this->getIsAutoList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getBuyTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['buy_time']) ? $data['buy_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setBuyTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    //统计盈亏数据
    public function statistics($stockInfo,$isUpdate = true,$num = null){
        $obj = $isUpdate == true ? $this : clone $this;
        if(isset($num) && is_numeric($num)){
            $obj->lever_num = $num;
        }
        //每股盈亏
        $income = $stockInfo['price'] - $obj->buy_price;
        //总收益
        $sumIncome = $income * $obj->lever_num;
        //历史总收益
        $sumIncomes = ($sumIncome + $obj->income_log);
        //收益比例 总收益/保证金
        $incomeRatio = sprintf('%.2f',$sumIncome / $obj->earnest_money);
        $obj->income = $sumIncome;
        $obj->income_log = $sumIncomes;
        $obj->income_ratio = $incomeRatio;
        return $obj;
    }

    //增加总市值
    public function addSumPrice($stockInfo){
        $this->sumPrice = sprintf('%.2f',$stockInfo['price'] * $this->lever_num);
        return $this;
    }


    //平仓数据修改
    public function pay($stockInfo,$conList,$pay_type = 1,$num = null){
        $userInfo = User::find($this->user_id);
        //计算盈余
        $this->statistics($stockInfo,true,$num)->addSumPrice($stockInfo);
        if(!empty($num)){
            $money = ($num * $this->buy_price)/10;
            updateMoney($userInfo,$money,'保证金');
        }
        //统计盈亏
        if( $this->income != 0 ){
            updateMoney($userInfo,$this->income,'盈亏');
        }
        //交易佣金
        updateMoney($userInfo,$this->sumPrice * $conList['commission'] * 0.01 * -1,'交易佣金');
        //印花税
        updateMoney($userInfo,$this->sumPrice * $conList['stamp_duty'] * 0.01 * -1,'印花税');
        //过户费
        updateMoney($userInfo,$this->sumPrice * $conList['transfer_fee'] * 0.01 * -1,'过户费');

        //完结订单
        $data = Db::name('strategy')->where('id',$this->id)->find();
        // $this->lever_num = $data['lever_num'] - $num;
        // $this->allowField(true)->save();
        
        $data['lever_num'] = $num;
        $data['sell_price'] = $stockInfo['price'];
        $data['income'] = $this->income;
        $data['income_ratio'] = $this->income_ratio;
        $data['status'] = 2;
        $data['pay_type'] = $pay_type;
        $data['pay_time'] = time();
        $data['createtime'] = time();
        unset($data['id']);
        Db::name('strategy')->insert($data);
        //统计盈亏
        $userInfo->cumulative_profit_loss += $this->income;
        $userInfo->save();
        return $this;
    }

    //加仓数据修改
    public function addNum($stockInfo,$num,$conList){
        $userInfo = User::find($this->user_id);
        //保证金
        $earnestMoney = $stockInfo['price'] * $num / 10;
        //管理费
        $managementExpense = $this->is_auto == 1 ? $earnestMoney * $conList['management_expense'] * 0.01 * 10 : 0;
        //建仓费
        $addWarehouse = $earnestMoney * 10 * $conList['add_warehouse'];
        if( ($earnestMoney + $managementExpense + $addWarehouse) > $userInfo->money ){
            throw new \Exception('余额不足');
        }

        $oldStrategyInfo = $this->statistics($stockInfo,false);
        //修改信息
        // $this->num += $num / 10;
        // $this->lever_num += $num;
        // $this->earnest_money += $earnestMoney;
        // $this->buy_price = $stockInfo['price'];
        // $this->buy_time = time();
        // $this->income_log += $oldStrategyInfo->income;//记录历史盈余
        // $this->save();

        $data = Db::name('strategy')->where('id',$this->id)->find();
        $data['num'] = $num / 10;
        $data['lever_num'] = $num;
        $data['earnest_money'] = $earnestMoney;
        $data['buy_price'] = $stockInfo['price'];
        $data['buy_time'] = time();
        $data['income_log'] = $oldStrategyInfo->income;
        $data['createtime'] = time();
        $data['status'] = 3;
        unset($data['id']);
        Db::name('strategy')->insert($data);
        //扣除余额
        updateMoney($userInfo,$earnestMoney * -1,'保证金');
        if( $addWarehouse > 0 ){
            updateMoney($userInfo,$addWarehouse * -1,'建仓费');
            //交易佣金
            updateMoney($userInfo,$stockInfo['price'] * $num * $conList['commission'] * 0.01 *-1,'交易佣金');
        }
        if( $managementExpense > 0 ){
            updateMoney($userInfo,$managementExpense * -1,'管理费');
        }
        return $this;
    }


}
